package com.burst.reptile.modular.zp.service.impl;

import java.util.Arrays;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.exception.CustomException;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.modular.zp.entity.ZpLabel;
import com.burst.reptile.modular.zp.mapper.ZpLabelMapper;
import com.burst.reptile.modular.zp.service.IZpLabelService;

import cn.hutool.core.util.StrUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-06-16
 */
@Service
public class ZpLabelServiceImpl extends ServiceImpl<ZpLabelMapper, ZpLabel> implements IZpLabelService {

	@Override
	public Page<ZpLabel> pageList(int page, int limit, ZpLabel label) {
		Page<ZpLabel> zpLabelpage = new Page<>(page, limit);
		return this.page(zpLabelpage, new QueryWrapper<ZpLabel>().orderByDesc("label_heat"));
	}

	@Override
	public Page<ZpLabel> pageList(Page<ZpLabel> page, ZpLabel label) {
		 QueryWrapper<ZpLabel> queryWrapper = new QueryWrapper<ZpLabel>();
		 String labelName = label.getLabelName();
		 if(StrUtil.isNotEmpty(labelName)) {
			 queryWrapper.like("label_name", labelName);
		 }
		 queryWrapper.orderByDesc("label_heat");
		return this.page(page, queryWrapper);
	}

	@Override
	public int deleteByIds(Long[] ids) {
		return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public String checkLabelKeyUnique(ZpLabel label) {
		Long labelId = ToolUtil.isEmpty(label.getLabelId()) ? -1L : label.getLabelId();
		ZpLabel info = this.baseMapper.selectOne(new QueryWrapper<ZpLabel>().eq("label_name", label.getLabelName()));
		if (ToolUtil.isNotEmpty(info) && info.getLabelId().longValue() != labelId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public int insertLabel(ZpLabel label) {
		return this.baseMapper.insert(label);
	}

	@Override
	public int updateLabel(ZpLabel label) {
		Integer labelId = label.getLabelId();
		if(ToolUtil.isEmpty(labelId)) {
			throw new CustomException("修改失败，缺少参数");
		}
		ZpLabel byId = this.getById(labelId);
		if(ToolUtil.isEmpty(byId)) {
			throw new CustomException("修改失败，资源不存在");
		}
		return this.baseMapper.updateById(label);
	}

}
